package com.dic.filter;

import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

import com.dic.dao.*;
import com.dic.exception.*;
import com.dic.service.UserService;

public class PriviledgeFilter implements Filter {
	private List<String> permissions = null; 
	
	public void init(FilterConfig config) throws ServletException {
		
	}
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
		//System.out.println("aa");
		HttpServletRequest request = (HttpServletRequest) req;
		String requestURI = (request.getRequestURI().replace(request.getContextPath() + "/", "")).replaceAll("\\.\\w+", "");
		requestURI = requestURI.replaceAll("\\w*/", "");
		String role = (String)request.getSession(true).getAttribute("role");
		String username = (String)request.getSession(true).getAttribute("username");
		//System.out.println("cc"+role+";"+username);
		boolean authentificated =false;
		try {
			UserService ser = new UserService();
			permissions= ser.getPermissions(role);//��ȡĳ��½�û��ܷ��ʵ�ҳ���б�
			//System.out.println(permissions.size());
			for(Iterator<String> it = permissions.iterator(); it.hasNext();) {
				String aa=(String)it.next();
				String bb=requestURI;
				//System.out.println("aa:"+aa);
			//	System.out.println("bb:"+bb);
				//System.out.println("cc:"+bb.equals(aa));
				//System.out.println("dd:"+(username!=null));
				if(bb.equals(aa) && username!=null){
					authentificated = true;
					//System.out.println("ee:"+authentificated);
					break;
		 	    }
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		//System.out.println("ff:"+authentificated);
		if(!authentificated)
			throw new RuntimeException(new LoginException("您无权访问该页面，请以合适的身份登录后查看。"));
		chain.doFilter(req, res);
	}
	public void destroy() {
		permissions = null;
	}
}



